package com.example.accountingapp;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import androidx.appcompat.app.AppCompatActivity;

public class SalaryIncomeActivity extends AppCompatActivity {

    private EditText etIncome;
    private DatabaseHelperIncome dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other_income);

        etIncome = findViewById(R.id.etIncome);
        Button btnSave = findViewById(R.id.btnSave);

        dbHelper = new DatabaseHelperIncome(this);

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveIncome();
            }
        });
    }

    private void saveIncome() {
        String income = etIncome.getText().toString().trim();
        String category = "薪资收入";
        String date = getCurrentDateTime();

        if (income.isEmpty()) {
            Toast.makeText(this, "请输入收入金额", Toast.LENGTH_SHORT).show();
            return;
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(DatabaseContractIncome.IncomeEntry.COLUMN_INCOME, income);
        values.put(DatabaseContractIncome.IncomeEntry.COLUMN_CATEGORY, category);
        values.put(DatabaseContractIncome.IncomeEntry.COLUMN_TIMESTAMP, date);
        values.put(DatabaseContractIncome.IncomeEntry.COLUMN_DATE, date);

        long newRowId = db.insert(DatabaseContractIncome.IncomeEntry.TABLE_NAME, null, values);

        if (newRowId != -1) {
            Toast.makeText(this, "收入记录保存成功", Toast.LENGTH_SHORT).show();
            etIncome.setText("");
        } else {
            Toast.makeText(this, "保存失败，请重试", Toast.LENGTH_SHORT).show();
        }

        db.close();
    }

    private String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date currentDate = new Date();
        return sdf.format(currentDate);
    }

    public void goBack(View view) {
        finish();
    }
}
